package com.dlyk.web;

import com.dlyk.model.Product;
import com.dlyk.query.ProductQuery;
import com.dlyk.result.R;
import com.dlyk.service.ProductService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品
 */
@RestController
public class ProductController {

    @Resource
    private ProductService productService;

    /**
     * 查询所有在售的产品
     */
    // 要想使用@PreAuthorize注解，需要在Spring Security配置类中使用@EnableMethodSecurity注解，开启方法级别的权限检查
    // 当前用户有 "product:list" 这个权限标识符时才可以访问这个控制器
    @PreAuthorize(value = "hasAuthority('product:list')")
    @GetMapping("/api/product/list")
    public R productListAllOnSale() {

        List<Product> allOnSaleProduct = productService.getAllOnSaleProduct();

        return R.OK(allOnSaleProduct);
    }

    /**
     * 查询所有产品
     */
    @PreAuthorize(value = "hasAuthority('product:list')")
    @GetMapping("/api/product/list/all")
    public R productListAll(@RequestParam(value = "current", required = false) Integer current) {

        // required = false  表示非必须，这个参数也可以不传，不传参数，默认查询第一页
        if (current == null) {
            current = 1;
        }

        PageInfo<Product> productPageInfo = productService.getProductListByPage(current);

        return R.OK(productPageInfo);
    }

    /**
     * 录入产品
     */
    @PreAuthorize(value = "hasAuthority('product:add')")
    @PostMapping("/api/product/add")
    public R addProduct(ProductQuery productQuery) {

        int add = productService.addProduct(productQuery);

        return add >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 编辑产品
     */
    @PreAuthorize(value = "hasAuthority('product:edit')")
    @PutMapping("/api/product/edit")
    public R editProduct(ProductQuery productQuery) {

        int edit = productService.editProduct(productQuery);

        return edit >= 1 ? R.OK() : R.FAIL();
    }

}

